package com.base.hong.ui.base

import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.base.hong.ext.showToast
import com.base.hong.ui.MainActivity
import com.htt.base_library.base.BaseActivity
import com.htt.base_library.base.BaseVModel
import com.htt.base_library.constant.BaseConstant
import com.htt.base_library.manager.ActivityManager
import com.htt.base_library.util.ClassUtil
import com.base.hong.utils.SPUtils
import com.htt.base_library.util.startActivity


/**
 *
 * Created by hong on 2021/7/13 9:46.
 *
 */
abstract class BaseVMActivity<VM : BaseVModel, VB : ViewBinding> : BaseActivity<VB>() {

    lateinit var viewModel: VM

    override fun initView(intent: Intent?, savedInstanceState: Bundle?) {
        initViewModel()
    }

    open fun initViewModel() {
        var classType = ClassUtil.getViewModel<VM>(this)
        classType?.let {
            viewModel = ViewModelProvider(this).get(classType)
            lifecycle.addObserver(viewModel)
            registerUIChange()
        }
    }

    /**
     * 注册 UI 事件
     */
    private fun registerUIChange() {
        viewModel.ui.showDialog.observe(this) {
            showLoadingDialog(it ?: "")
        }
        viewModel.ui.dismissDialog.observe(this) {
            dismissLoadingDialog()
        }
        viewModel.ui.errorEvent.observe(this) {
            dismissLoadingDialog()
            when (it.code) {
                BaseConstant.HTTP_CODE_LOGOUT -> {
                    showToast("当前登录状态过期，请您重新登录!")
                    skipLogin()
                }
                BaseConstant.HTTP_CODE_CLEAR_ACCOUNT -> {
                    showToast("该账户已注销 !")
                    skipLogin()
                }
                else -> {
                    showError(it.msg, it.code)
                }
            }
        }
    }

    open fun skipLogin() {
        SPUtils.clean()
        ActivityManager.finishAllActivity()
        startActivity<MainActivity>()
    }

    open fun showError(msg: String, code: Int) {
        showToast(msg)
    }

}